package com.hilinos.gb.gb28181.utils;

import com.hilinos.gb.gb28181.config.SipConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class SsrcUtils implements ApplicationRunner {

    @Autowired
    private SipConfig sipConfig;

    private static String ssrcPrefix;

    private static final List<String> SSRC_LIST = new ArrayList<>();

    private static final Object LOCK = new Object();

    @Override
    public void run(ApplicationArguments args) throws Exception {
        new Thread(() -> {
            synchronized (LOCK) {
                ssrcPrefix = sipConfig.getSipDomain().substring(3, 8);
                for (int i = 1; i < 10000; i++) {
                    if (i < 10) {
                        SSRC_LIST.add("000" + i);
                    } else if (i < 100) {
                        SSRC_LIST.add("00" + i);
                    } else if (i < 1000) {
                        SSRC_LIST.add("0" + i);
                    } else {
                        SSRC_LIST.add(String.valueOf(i));
                    }
                }
            }
        }).start();

    }

    /**
     * 获取后四位数SN,随机数
     * 把第一个ssrc放到最后
     */
    private static String getSN() {
        synchronized (LOCK) {
            String sn = SSRC_LIST.get(0);
            SSRC_LIST.remove(0);
            SSRC_LIST.add(sn);
            return sn;
        }
    }

    /**
     * 获取视频预览的SSRC值,第一位固定为0
     */
    public static String getPlaySsrc() {
        return "0" + ssrcPrefix + getSN();
    }

    /**
     * 获取录像回放的SSRC值,第一位固定为1
     */
    public static String getPlayBackSsrc() {
        return "1" + ssrcPrefix + getSN();
    }
}
